﻿/*
 * Copyright 2009 - 2010 eScience Institute
 *
 * This file is part of SqlShare.
 *
 * SqlShare is free software: you can redistribute it and/or modify it under the terms 
 * of the GNU General Public License as published by the Free Software Foundation, 
 * either version 3 of the License, or (at your option) any later version.
 *
 * SqlShare is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with 
 * SqlShare. If not, see http://www.gnu.org/licenses/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using SqlShareAPI;

namespace WebQueryRole
{
    public partial class sqloutput : System.Web.UI.Page
    {
        
        
        protected void Page_Load(object sender, EventArgs e)
        {
            UserSession session = WebAuthentication.IsLoggedIn(this, CloudUtil.CreateSSAPIFactory());
            if (session == null)
            {
                return;
            }

            string outType = Request["output_type"];
            string sql = Request["sql_code"];

            if (outType == null)
            {
                return;
            }

            if (!String.IsNullOrEmpty(sql))
            {
                PrintTabDelimitedFile(sql, session);
            }

            session.Close();
        }       

        private void PrintTabDelimitedFile(string sql, UserSession session)
        {
            SqlDataAdapter da = new SqlDataAdapter(sql, session.ContentSqlConnection);

            DataSet ds = new DataSet();
            DataTable dt = null;
            try
            {
                da.Fill(ds);
                dt = ds.Tables[0];
            }
            catch (Exception e)
            {
                errorDiv.InnerHtml = e.Message;
                return;
            }


            Response.Clear();
            Response.ContentType = "APPLICATION/OCTET-STREAM";
            Response.AddHeader("Content-Disposition", "attachment;filename=\"output.tab\"");
            Response.AddHeader("content-type", "text/csv");

            using (StreamWriter writer = new StreamWriter(Response.OutputStream))
            {

                int iColCount = dt.Columns.Count;
                for (int i = 0; i < iColCount; i++)
                {
                    writer.Write(dt.Columns[i]);
                    if (i < iColCount - 1)
                    {
                        writer.Write("\t");
                    }
                }
                writer.Write(writer.NewLine);

                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            writer.Write(dr[i].ToString());
                        }
                        if (i < iColCount - 1)
                        {
                            writer.Write("\t");
                        }
                    }

                    writer.Write(writer.NewLine);
                }

                writer.Close();
            }            

            Response.End();
        }      
    }
}
